﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    public class IndexPropertyReplacementParser : ILineParser
    {
        private static readonly HashSet<string> _IndexProperties;
        static IndexPropertyReplacementParser()
        {
            _IndexProperties = new HashSet<string>()
                {
                    "Bookmarks","Sections","Headers","FormFields","CaptionLabels","AutoTextEntries","Dialogs"
                };
        }

        private static readonly Regex PropertyPattern =
            new Regex(
                @"\b(?<property>[a-zA-Z]\w+)\((?<index>[^\(\)]+)\)",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            success = true;
            return PropertyPattern.Replace(lineContent, m =>
            {
                if (_IndexProperties.Contains(m.Groups["property"].Value))
                {
                    return string.Format("{0}[{1}]", m.Groups["property"].Value, m.Groups["index"].Value);
                }
                else
                {
                    return m.Value;
                }
            });
        }
    }
}
